package com.machinecontroller;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Environment;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.machinecontroller.constant.FileConstant;
import com.machinecontroller.constant.McConfig;
import com.machinecontroller.constant.UrlConstant;
import com.machinecontroller.ex.CrashHandler;
import com.machinecontroller.receiver.ServiceMonitorBroadCasrReceiver;
import com.machinecontroller.service.UpdateService;
import com.machinecontroller.utils.DevUtil;
import com.machinecontroller.utils.Logger;
import com.machinecontroller.utils.SpUtil;
import com.sunshine.retrofit.HttpBuilder;
import com.sunshine.retrofit.HttpUtil;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.tinker.loader.app.DefaultApplicationLike;

import java.io.File;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by zhangxuehui on 2017/12/11.
 */

public class SampleApplicationLike extends DefaultApplicationLike {

    private static final String TAG = SampleApplicationLike.class.getSimpleName();
    public static SampleApplicationLike mInstance;
    public String registrationId;
    private Application mContext;

    public SampleApplicationLike(Application application, int tinkerFlags,
                                 boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime,
                                 long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        this.mContext = (Application) getApplication().getApplicationContext();
        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(mContext);            // 初始化 JPush
        JPushInterface.setAlias(mContext, 1010, DevUtil.getImei(mContext));
        CrashHandler.getInstance().init(mContext);
        registerBroadCastReceiver();
        initBugly();
        Fresco.initialize(mContext);
        registrationId = JPushInterface.getRegistrationID(mContext);
        Logger.e(TAG, "=======>" + registrationId);
        SpUtil.put(mContext, McConfig.MC_REGISTRATION_ID_NAME, registrationId);
        //初始化网络请求
        new HttpUtil.SingletonBuilder(getApplication(), UrlConstant.BASE_URL)
                .build();
    }

    /**
     * 注册广播
     */
    private void registerBroadCastReceiver() {
        IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
        ServiceMonitorBroadCasrReceiver receiver = new ServiceMonitorBroadCasrReceiver();
        this.mContext.registerReceiver(receiver, filter);
    }

    private void initBugly() {
        /**************************
         *  配置热更新              *
         **************************/
        // 设置是否开启热更新能力，默认为true
        Beta.enableHotfix = true;
        // 设置是否自动下载补丁，默认为true
        Beta.canAutoDownloadPatch = true;
        // 设置是否自动合成补丁，默认为true
        Beta.canAutoPatch = true;
        // 设置是否提示用户重启，默认为false
        Beta.canNotifyUserRestart = false;
        // 设置开发设备，默认为false，上传补丁如果下发范围指定为“开发设备”，需要调用此接口来标识开发设备
        Bugly.setIsDevelopmentDevice(mContext, BuildConfig.IS_LOG_DEBUG);

        /**************************
         *  配置强制升级            *
         **************************/
        // 自动初始化开关
        Beta.autoInit = true;
        // 自动检查更新开关
        Beta.autoCheckUpgrade = true;
        // 升级检查周期设置，设置升级检查周期为60s(默认检查周期为0s)，60s内SDK不重复向后台请求策略);
        Beta.upgradeCheckPeriod = 0 * 1000;
        // 延迟初始化
        Beta.initDelay = 4 * 1000;
        // 设置sd卡的Download为更新资源存储目录
        Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        //设置开启显示打断策略,开启后没次检查更新，都会显示弹窗
        Beta.showInterruptedStrategy = false;
        /*在application中初始化时设置监听，监听策略的收取*/
        Beta.upgradeListener = (ret, strategy, isManual, isSilence) -> {
            if (strategy != null) {
                Logger.e(TAG, "有更新");
                /**
                 * 启动自定义下载程序
                 */
//                if (TextUtils.isEmpty(SpUtil.getAppPath(getApplication()))) {
////                    Beta.startDownload();
//                    downloadApk();
//                } else {
//                    File file = new File(SpUtil.getAppPath(getApplication()));
//                    if (!file.exists()) {
////                        Beta.startDownload();
//                        downloadApk();
//                    } else {
//                        Intent i1 = new Intent(getApplication(), UpdateService.class);
//                        getApplication().startService(i1);
//                    }
//                }
            } else {
                Logger.e(TAG, "没有更新");
            }
        };
        // 设置是否是否在消息通知中显示下载进度
        Beta.enableNotification = false;
        // 设置Wifi下自动下载
        Beta.autoDownloadOnWifi = false;
        // 设置是否显示弹窗中的apk信息
        Beta.canShowApkInfo = false;
        // false 关闭热更新能力
        Beta.enableHotfix = true;
        Beta.strToastYourAreTheLatestVersion = "";
        Beta.strToastCheckingUpgrade = "";
        Beta.strToastCheckUpgradeError = "";
        // 这里实现SDK统一初始化，appId替换成你的在Bugly平台申请的appId
        Bugly.init(mContext, "807d5cc6d1", BuildConfig.IS_LOG_DEBUG);
    }

    private boolean isDownload; //是否正在下载

    private void downloadApk() {
        synchronized (this) {
            if (!isDownload) {
                new HttpBuilder("https://s.beta.myapp.com/myapp/rdmexp/exp/file/commachinecontroller_21_1ed38101-0854-5cc6-b801-21edc3050356.apk")
                        .path(FileConstant.APP_PATH + File.separator + "mc.apk")
                        .progress(p -> {
                            Logger.e("aaa", 100 * p + "%");
                            isDownload = true;
                        })
                        .error(t -> isDownload = false)
                        .success(s -> {
                            //返回path
                            Logger.e("aaa", s);
                            isDownload = false;
                            SpUtil.putAppPath(getApplication(), s);
                            Intent i1 = new Intent(getApplication(), UpdateService.class);
                            getApplication().startService(i1);
                        })
                        .download();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);

        // 安装tinker
        // TinkerManager.installTinker(this); 替换成下面Bugly提供的方法
        Beta.installTinker(this);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }

}

